'use strict';
const ObjectID = require('mongodb').ObjectID;
const collectionName ="job";
module.exports = app => {
  class TemService extends app.Service {       
    * getList(option){ 
        let pageNum=1; 
        const defaultOption = {
            query: {},
            skip: 0,
            limit: 2,
            project: {},
            sort: {}
        };
   
        if (option.hasOwnProperty("pageSize")) {
            defaultOption.limit = parseInt(option.pageSize);
        }

        if (option.hasOwnProperty("pageNum")) {
            let npage = parseInt(option.pageNum);
            if (npage > 1) {
                defaultOption.skip = (npage - 1) * defaultOption.limit - 1;
            }
            pageNum = npage;

        }

        Object.assign(defaultOption, option); 
     
       
        const count = yield app.mongo.count(collectionName, defaultOption);

        let totalPage = Math.ceil(count / defaultOption.limit);

        let curPage = pageNum > totalPage ? totalPage : pageNum;

        defaultOption.skip = (curPage - 1) * defaultOption.limit;

        const result = yield app.mongo.find(collectionName, defaultOption);       
        
        return { 
            records: result,
            total: count,
            current: curPage
        };
    }

    * getOneByOption(doc){ 
        const result = yield app.mongo.find(collectionName, { query: { _id: ObjectID.createFromHexString(doc.id) }});
        return result;
    }
    
    * add(doc){
        const result = yield app.mongo.insertOne(collectionName, { doc });        
        const insertSuccess = result.insertedCount === 1 ;
        return insertSuccess;
    }

    * delete(doc){       
        const result = yield app.mongo.findOneAndDelete(collectionName, { 
            filter: {}, 
            options: { _id: ObjectID.createFromHexString(doc.id) } 
        });
        const delSuccess = result.ok === 1;
        return delSuccess;
    }

    * update(id,doc){
        const result = yield app.mongo.findOneAndUpdate(collectionName, { 
            filter: { _id: new ObjectID(id)},
            update: doc,
            options: { _id: new ObjectID(id)}
         });
        console.log(result);
         
        const updateSuccess = result.ok === 1;
        return updateSuccess;
    }

  }
  return TemService;
};
